package com.PDP.security.audit;

import com.PDP.DTO.AuditDTO;
import com.PDP.security.user.UserService;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;

@Service
@AllArgsConstructor
public class AuditService {
    @Autowired
    private final AuditRepository auditRepository;
    @Autowired
    private final UserService userService;

    public Iterable<AuditDTO> getAll(){

        ArrayList<AuditDTO> auditDTOS=new ArrayList<>();
        for(AuditionEntity a:auditRepository.findAll()){
            AuditDTO ad=new AuditDTO();
            ad.setDate(a.getDate());
            ad.setAction(a.getAction());
            ad.setName(a.getName());
            ad.setEntity(a.getEntity());
            String ln=userService.getById(a.getUserId())==null?a.getLastUserName():userService.getById(a.getUserId()).getName();
            ad.setLastUserName(ln);
            a.setLastUserName(ln);
            auditRepository.save(a);
            auditDTOS.add(ad);
        }
        return auditDTOS;

    }
}
